package org.example;

import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.*;

public class AppSimpleWebServer {
    private static final int PORT = 8080;


    private static String getNowString() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

//这是静态方法.如果使用它做响应,则每次响应都是不一样的,方法每次都会入栈执行
    private static String getResponse() {
        return "HTTP/1.1 200 OK\r\n" +
                "Content-Type: text/html; charset=utf-8\r\n" +
                "Connection: close\r\n\r\n" +
                "<!DOCTYPE html><html><head><title>Hello World</title></head>" +
                "<body><h1>Hello World</h1><p>无论您请求什么，我都会返回这个页面.当前时间:" + getNowString() + "</p></body></html>";
    }


//这是静态字段,只在类加载的时候初始化一次,只会执行一次.如果使用它做响应,则每次响应都是一样的
    private static String getResponse = "HTTP/1.1 200 OK\r\n" +
            "Content-Type: text/html; charset=utf-8\r\n" +
            "Connection: close\r\n\r\n" +
            "<!DOCTYPE html><html><head><title>Hello World</title></head>" +
            "<body><h1>Hello World</h1><p>无论您请求什么，我都会返回这个页面.当前时间:" + getNowString() + "</p></body></html>";


    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(1);

        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("服务器启动在端口: " + PORT);
            System.out.println("访问地址: http://localhost:" + PORT);

            while (true) {
                try {
                    Socket clientSocket = serverSocket.accept();
                    pool.execute(() -> handleRequest(clientSocket));
                } catch (IOException e) {
                    System.err.println("接受连接错误: " + e.getMessage());
                }
            }
        } catch (IOException e) {
            System.err.println("无法启动服务器: " + e.getMessage());
        } finally {
            pool.shutdown();
        }
    }

    private static void handleRequest(Socket clientSocket) {
        System.out.println("------------------------------收到新的请求------------------------------");
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));
             OutputStream out = clientSocket.getOutputStream()) {

            System.out.println("读内容");

            // 读取请求头（仅用于日志）
            String line;
            while ((line = in.readLine()) != null && !line.isEmpty()) {
                System.out.println("请求: " + line);
            }

            // 发送响应
            out.write(getResponse().getBytes("UTF-8"));
            out.flush();
        } catch (IOException e) {
            System.err.println("处理请求错误: " + e.getMessage());
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                System.err.println("关闭连接错误: " + e.getMessage());
            }
        }
    }
}